const { spawn } = require('child_process');
const path = require('path');

// 启动后端服务
function startBackend() {
  const backendPath = __dirname;
  const serverPath = path.join(backendPath, 'server.js');
  
  console.log('Starting backend service...');
  console.log('Backend path:', backendPath);
  console.log('Server path:', serverPath);
  
  // 使用 Electron 的 Node.js 可执行文件路径
  const nodePath = process.execPath;
  // 直接运行 server.js 而不是再次启动 start.js
  const backendProcess = spawn(nodePath, [serverPath], { 
    cwd: backendPath,
    stdio: 'inherit' // 继承父进程的输入输出
  });
  
  backendProcess.on('close', (code) => {
    console.log(`Backend process exited with code ${code}`);
  });
  
  backendProcess.on('error', (err) => {
    console.error('Failed to start backend process:', err);
  });
  
  return backendProcess;
}

// 启动后端服务
const backendProcess = startBackend();

// 监听进程退出事件
process.on('exit', () => {
  if (backendProcess) {
    backendProcess.kill();
  }
});

process.on('SIGINT', () => {
  if (backendProcess) {
    backendProcess.kill();
  }
  process.exit(0);
});

process.on('SIGTERM', () => {
  if (backendProcess) {
    backendProcess.kill();
  }
  process.exit(0);
});